import zhCnLocale from 'element-plus/es/locale/lang/zh-cn'
import zhTwLocale from 'element-plus/es/locale/lang/zh-tw'
import enLocale from 'element-plus/es/locale/lang/en'
import zhCn from '@/router/lang/zh-cn';
import {createI18n} from 'vue-i18n';

import pinia from '@/stores/index';
import {storeToRefs} from 'pinia';
import {useSettingStore} from "@/stores/modules/setting"
import {getI18nConfigList} from '@/api/utils'

// 读取 pinia 默认语言
const stores = useSettingStore(pinia);
const {globalI18n, languages} = storeToRefs(stores);

const messages: any = {};
const element: any = {en: enLocale, 'zh-cn': zhCnLocale, 'zh-tw': zhTwLocale};
const itemize: any = {en: [] as any[], 'zh-cn': [] as any[], 'zh-tw': [] as any[]};

// 申明 对象
declare type EmptyObjectType<T = any> = {
    [key: string]: T;
};

// 合并数组对象（非标准数组对象，数组中对象的每项 key、value 都不同）
function mergeArrObj(list: any, key: string) {
    let obj = {};
    list[key].forEach((i: EmptyObjectType) => {
        obj = Object.assign({}, obj, i);
    });
    return obj;
}

for (const key in itemize) {
    const data = {
        name: key,
        el: element[key].el,
    };

    //默认简体中文字典，后期需注释
    if (key === 'zh-cn') {
        Object.assign(data, zhCn);
    }

    messages[key] = {
        ...data,
        ...mergeArrObj(itemize, key),
    };
}

// console.log(messages)

// 创建 i18n 实例
export const i18n = createI18n({
    locale: globalI18n.value, // 设置默认语言
    legacy: false,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true,
    fallbackWarn: false,
    fallbackLocale: zhCnLocale.name,
    messages,
});

export function $t(key: string, values?: any) {
    return i18n.global.t(key, values);
}

//
// (async function () {
//     await fetchI18n()
// })()

function flattenToNested(flatObject: Record<string, any>): Record<string, any> {
    const nestedObject: Record<string, any> = {};

    for (const key in flatObject) {
        if (!flatObject.hasOwnProperty(key)) continue;

        const keys = key.split('.');
        let currentLevel = nestedObject;

        for (let i = 0; i < keys.length; i++) {
            const part = keys[i];

            if (i === keys.length - 1) {
                currentLevel[part] = flatObject[key];
            } else {
                if (!currentLevel[part]) {
                    currentLevel[part] = {};
                }
                currentLevel = currentLevel[part];
            }
        }
    }

    return nestedObject;
}

// 远程获取i18n
export async function fetchI18n() {
    try {
        type InfoI18n = Record<string, object>;

        // const languages: Record<string, string> = {
        //     CHS: 'zh-cn',
        //     CHT: 'zh-tw',
        //     EN: 'en'
        // }

        const data = await getI18nConfigList() as any;
        let infoI18n: InfoI18n = Array.isArray(data) ? data[0] : data;
        if (typeof infoI18n.CHS != 'object') {
            infoI18n = {
                CHS: {
                    'router.login': '登录',
                    'router.home': '首页'
                },
                CHT: {
                    'router.login': '登入',
                    'router.home': '首頁'
                },
                EN: {
                    'router.login': 'Login',
                    'router.home': 'Home'
                }
            }
        }

        const messageLocal: any = {};
        for (const key in infoI18n) {
            const language: string = languages.value.find((item: any) => item.value === key || item.alias === key)?.value || key;
            const flatMessages: object = infoI18n[key];
            const nestedMessages = flattenToNested(flatMessages);
            messageLocal[language] = {
                name: language,
                el: element[language].el,
                ...nestedMessages,
            };
            // console.log(element[language].el)
        }

        for (const key in messageLocal) {
            i18n.global.mergeLocaleMessage(key, messageLocal[key]);
        }
        i18n.global.locale.value = globalI18n.value;
    } catch (e) {
        console.log(e);
    }
}
